package com.cyys.modules.system.controller.org;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyys.common.annotation.SystemLog;
import com.cyys.common.dataScope.DataScope;
import com.cyys.common.ql.AR;
import com.cyys.common.ql.JSONData;
import com.cyys.common.utils.StringUtil;
import com.cyys.common.validate.Detail;
import com.cyys.common.validate.Insert;
import com.cyys.modules.core.controller.BaseAction;
import com.cyys.modules.core.sysParam.OrgUtil;
import com.cyys.modules.system.model.org.Org;
import com.cyys.modules.system.service.org.OrgService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/sys/org")
public class OrgAction extends BaseAction {

	@Resource
	private OrgService orgService;

	@RequestMapping(value = "/add/input",method = RequestMethod.GET)
	@RequiresPermissions(value = { "sys:org:add","sys:org:menu" },logical = Logical.OR)
	public String input(Org org, Model model) throws Exception {
		model.addAttribute("org", org);
		return "module/system/org/org-input";
	}

	@ResponseBody
	@PostMapping("/add/save")
	@RequiresPermissions(value = { "sys:org:add","sys:org:menu" },logical = Logical.OR)
	@SystemLog(module = "机构管理", methods = "机构管理-保存机构管理")
	public AR save(@Validated(Insert.class)Org org) throws Exception {
		return orgService.save(org);
	}

	@ResponseBody
	@PostMapping("/edit/save")
	@RequiresPermissions(value = { "sys:org:edit","sys:org:menu" },logical = Logical.OR)
	@SystemLog(module = "机构管理", methods = "机构管理-保存机构管理")
	public AR edit(@Validated(Detail.class)Org org) throws Exception {
		return orgService.save(org);
	}

	@RequestMapping(value = "/edit/input",method = RequestMethod.GET)
	@RequiresPermissions(value = { "sys:org:edit","sys:org:menu" },logical = Logical.OR)
	public String editInput(Org org, Model model) throws Exception {
		if (org != null && org.getId() != null) {
			org = orgService.getById(org.getId());
			model.addAttribute("org", org);
		}
		return "module/system/org/org-input";
	}

	@GetMapping("/list")
	@RequiresPermissions("sys:org:menu")
	public String list(Model model) {
		return "module/system/org/org-list";
	}

	@ResponseBody
	@PostMapping("/list/listInfo")
	@RequiresPermissions(value = { "sys:org:list","sys:org:menu" },logical = Logical.OR)
	@SystemLog(module = "机构管理", methods = "机构管理-查询机构管理")
		public String orglist(Org org, Page page) throws Exception {
		QueryWrapper<Org> qw = new QueryWrapper<>();
		qw.setEntity(org);
		qw.orderByAsc("parent_id").orderByAsc("sort");
		DataScope dataScope= new DataScope();
		dataScope.setScopeName("id");
		return JSONData.toLayerData(orgService.selectPageByScope(page , qw, dataScope));
	}

	@ResponseBody
	@PostMapping("/del/deleteById")
	@RequiresPermissions(value = { "sys:org:del","sys:org:menu" },logical = Logical.OR)
	@SystemLog(module = "机构管理", methods = "机构管理-删除机构管理")
	public AR deleteById(String id) throws Exception {
		return orgService.deleteById(id);
	}

	@ResponseBody
	@PostMapping("/del/deleteByIds")
	@RequiresPermissions(value = { "sys:org:del","sys:org:menu" },logical = Logical.OR)
	@SystemLog(module = "机构管理", methods = "机构管理-批量删除机构管理")
	public AR deleteByIds(String ids) throws Exception {
		return orgService.deleteByIds(ids);
	}

	@ResponseBody
	@RequestMapping("/list/listAllTree")
	public String listAllTree(Org org,Boolean queryTop,Boolean extendAll) throws Exception {
		List<Org> orgTree = orgService.listAllTree(new QueryWrapper(org));
		String orgArray = "[";
		String roleScope = getUser().getType();
		if (roleScope.equals("1") && queryTop != null && queryTop) {
			orgArray += "{id:\"0\"," + "pId:\"\",name:\"顶级节点\"";
			orgArray += ",isParent:false"; //这里为true的话，前台顶级节点一直点一直有
			orgArray += ",dropRoot:false";
			orgArray += ",childOuter:false";
			orgArray += ",open:true},";
		}
		orgArray += getOrgArray(orgTree, extendAll);
		int indx = orgArray.lastIndexOf(",");
		if (indx != -1)
			orgArray = orgArray.substring(0, indx);
		orgArray += "]";
		return orgArray;
	}


	/**
	 * @param parentId 父节点编号
	 * @param queryTop 是否查询顶级节点
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/list/getByParentId")
	public String getByParentId(String parentId, Boolean queryTop, Boolean extendAll) throws Exception {
		if (queryTop == null) { // 是否查询顶级节点
			queryTop = true;
		}
		List<Org> orgList = orgService.listByParentId(parentId);
		String orgArray = "[";
		if (queryTop) {
			orgArray += "{id:\"0\"," + "pId:\"\",name:\"顶级节点\"";
			orgArray += ",isParent:false"; //这里为true的话，前台顶级节点一直点一直有
			orgArray += ",dropRoot:false";
			orgArray += ",childOuter:false";
			orgArray += ",open:true},";
		}
		if(StringUtil.isNotEmpty(parentId) && !parentId.equals("0") ){
			Org org = OrgUtil.get(parentId);
			orgArray += "{id:\"" + org.getId() + "\"," + "pId:\"" + org.getParentId() + "\",name:\"" + org.getName() + "\",type:\"" + org.getType() + "\"";
			orgArray += ",isParent:false"; //这里为true的话，前台顶级节点一直点一直有
			orgArray += ",dropRoot:false";
			orgArray += ",childOuter:false";
			orgArray += ",open:true},";
		}
		orgArray += getOrgArray(orgList, extendAll);
		int indx = orgArray.lastIndexOf(",");
		if (indx != -1)
			orgArray = orgArray.substring(0, indx);
		orgArray += "]";
		return orgArray;
	}
	private String getOrgArray(List<Org> list,Boolean extendAll) {
		String orgArray = "";
		for (int i = 0; i < list.size(); i++) {
			Org t = list.get(i);
			orgArray += "{id:\"" + t.getId() + "\"," + "pId:\"" + t.getParentId() + "\",name:\"" + t.getName() + "\",type:\"" + t.getType() + "\"";
			if (t.getHasChild() == 1) {
				orgArray += ",dropRoot:false";
				//打开树
				orgArray += ",open:true";
				orgArray += ",childOuter:false";
			} else {
				orgArray += ",dropInner:false,childOuter:false";
			}
			if (t.getChildren() != null && t.getChildren().size() > 0) {
				if((extendAll !=null && extendAll) || (t.getIsRoot() != null && t.getIsRoot()))
					orgArray += ",open:true},";
				else
					orgArray += "},";
				orgArray += getOrgArray(t.getChildren(),extendAll);
			} else {
				orgArray += "},";
			}
		}
		return orgArray;
	}

	@RequestMapping("select-member")
	public String selectMember(Model model,String orgId,Integer selType,String teamId) {
		model.addAttribute("orgId", orgId);
		model.addAttribute("selType", selType);
		model.addAttribute("teamId", teamId);
		return "module/system/org/select-member";
	}


	@RequestMapping("setOrg")
	public String setOrg(Model model, Boolean queryTop) {
		model.addAttribute("queryTop", queryTop);
		return "module/system/org/set-org";
	}
}
